package net.wofly.sale.report.service.impl;

import net.wofly.common.util.DateUtil;
import net.wofly.common.util.Identities;
import net.wofly.sale.report.domain.CardExchangeDailyReport;
import net.wofly.sale.report.repository.CardExchangeDailyReportRepository;
import net.wofly.sale.report.service.ICardExchangeDailyReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

@Service("iCardExchangeDailyReportService")
@Transactional
public class CardExchangeDailyReportServiceImpl implements ICardExchangeDailyReportService {

	@Autowired
	CardExchangeDailyReportRepository cardExchangeDailyReportRepository;

	@Override
	public CardExchangeDailyReport save(CardExchangeDailyReport entity) {
		return cardExchangeDailyReportRepository.save(entity);
	}

	@Override
	public void delete(CardExchangeDailyReport entity) {
		cardExchangeDailyReportRepository.delete(entity);
	}

	@Override
	public void delete(String key) {
		cardExchangeDailyReportRepository.delete(key);
	}

	@Override
	public CardExchangeDailyReport findOne(String key) {
		return cardExchangeDailyReportRepository.findOne(key);
	}

	@Override
	public List<CardExchangeDailyReport> save(List<CardExchangeDailyReport> entityList) {
		return (List<CardExchangeDailyReport>) cardExchangeDailyReportRepository.save(entityList);
	}
	
	/**
	 * 根据时间生成日报
	 *
	 * @param countDate
	 */
	@Override
	public void generateCardExchangeDailyReport(Long countDate) {
		List<CardExchangeDailyReport> cardExchangeDailyReports = cardExchangeDailyReportRepository.findByCountDate(countDate, DateUtil.processEndTime(new Date(countDate)).getTime());

		if (cardExchangeDailyReports.size() == 0) {
			return;
		}

		cardExchangeDailyReportRepository.deleteByCountDate(countDate);

		for(CardExchangeDailyReport report : cardExchangeDailyReports) {
			report.setCardExchangeDailyReportID(Identities.uuid2());
			report.setModifyDate(System.currentTimeMillis());
			report.setCountDate(countDate);
		}

		cardExchangeDailyReportRepository.save(cardExchangeDailyReports);
	}

	@Override
	public List<CardExchangeDailyReport> findByUserIDAndCountDate(String userID, Long countDate) {
		return cardExchangeDailyReportRepository.findByUserIDAndCountDate(userID, countDate);
	}
}
